/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Tri;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import server.entity.CreatesContest;
import server.process.ProcessBeanLocal;
import server.process.ReportTopContest;

/**
 *
 * @author Hoang
 */
public class TriController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            if (!isMultiPart) {
                String action = request.getParameter("action");
                if (action.equals("Create Contest")) {
                    String txtNameContest = request.getParameter("txtNameContest");
                    String txtContent = request.getParameter("txtContent");
                    String txtRequirement = request.getParameter("txtRequirement");
                    String txtFromDate = request.getParameter("txtFromDate");
                    String txtToDate = request.getParameter("txtToDate");
//---------------------------------------------------------------------------------------
                    Context ctx = new InitialContext();
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) ctx.lookup("ProcessLocalJNDI");
                    tsbl.insertContest(txtNameContest, txtContent, txtRequirement, txtFromDate, txtToDate, true);
//--------------------------------------------------------------------------------------
                    out.print("Insert OK!");
                } else if (action.equals("ViewAllContest")) {
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    //     UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
                    //      ut.begin();
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    java.util.Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                    String dates = sdf.format(date);
                    System.out.println(dates);

//                    boolean test = tsbl.checkStatusContest(dates);
//                    System.out.println(test);

                    Collection result = tsbl.viewAllContest();
                    System.out.print(result);
                    request.setAttribute("ShowContest", result);
//---------------------------------------------------------------------------------
                    RequestDispatcher rd = request.getRequestDispatcher("ViewAllContest.jsp");
                    rd.forward(request, response);
                    //        ut.commit();
                } else if (action.equals("ViewRegistryContest")) {
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    Collection result = tsbl.viewRegContest();
                    request.setAttribute("ViewRegistryContest", result);
                    RequestDispatcher rd = request.getRequestDispatcher("RegistryContest.jsp");
                    rd.forward(request, response);
                } else if (action.equals("OK")) {
                    String idS = request.getParameter("txtId");
                    int id = Integer.parseInt(idS);
                    String name = request.getParameter("txtName");
                    String content = request.getParameter("txtContent");
                    String txtFromDate = request.getParameter("txtFromDate");
                    String txtToDate = request.getParameter("txtToDate");
                    String statusS = request.getParameter("txtCheck");
                    boolean status;
                    if (statusS != null) {
                        status = true;
                    } else {
                        status = false;
                    }
//----------------------------------------------------------------------
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    tsbl.updateContest(id, name, content, txtFromDate, txtToDate, status);
                    RequestDispatcher rd = request.getRequestDispatcher("TriController?action=ViewAllContest");
                    rd.forward(request, response);
                } else if (action.equals("I Agree")) {
                    String username = request.getParameter("txtUserName");
                    String txtIdContest = request.getParameter("txtIdContest");
                    int idContest = Integer.parseInt(txtIdContest);
                    String txtCheck = request.getParameter("txtCheck");
                    boolean check = false;
                    if (txtCheck != null) {
                        check = true;
                    }
//--------------------------------------------------------------------------
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    boolean test = tsbl.registryContest(check, idContest, username);
                    if (test) {
                        out.print("Registry OK");
                    } else {
                        out.print("You are registered");
                    }
                    HttpSession session = request.getSession();
                    RequestDispatcher rd = request.getRequestDispatcher("TriController?action=ViewUpload&txtUsername=" + session.getAttribute("username").toString() + "&txtIdContest=" + txtIdContest);
                    rd.forward(request, response);
                } else if (action.equals("ViewUpload")) {
                    String name = request.getParameter("txtUsername");
                    String idCon = request.getParameter("txtIdContest");
                    int idContest = Integer.parseInt(idCon);
//       -------------------------------------------------------
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    Collection result = tsbl.viewUpload(name, idContest);
                    System.out.println(result);
                    request.setAttribute("ViewUpload", result);
                    RequestDispatcher rd = request.getRequestDispatcher("UploadImage.jsp");
                    rd.forward(request, response);
                } else if (action.equals("ViewImage")) {
                    String idCon = request.getParameter("idContest");
                    int idContest = Integer.parseInt(idCon);
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    Collection viewImage = tsbl.ViewAllImage(idContest);
                    request.setAttribute("ViewImage", viewImage);
                    System.out.println(viewImage);
                    RequestDispatcher rd = request.getRequestDispatcher("ViewImage.jsp");
                    rd.forward(request, response);
                } else if (action.equals("Vote")) {
                    String txtUsername = request.getParameter("txtUsername");
                    String txtIdImgContest = request.getParameter("txtIdImgContest");
                    String txtInfoImage = request.getParameter("txtInfoImage");
                    String txtImage = request.getParameter("txtImage");
                    request.setAttribute("txtUsername", txtUsername);
                    request.setAttribute("txtIdImgContest", txtIdImgContest);
                    request.setAttribute("txtInfoImage", txtInfoImage);
                    request.setAttribute("txtImage", txtImage);
                    RequestDispatcher rd = request.getRequestDispatcher("Vote.jsp");
                    rd.forward(request, response);
                } else if (action.equals("Submit Vote")) {
                    String name = request.getParameter("txtUsername");
                    String idImage = request.getParameter("txtIdImgContest");
                    int idImgContest = Integer.parseInt(idImage);
                    String markS = request.getParameter("radVote");
                    int mark = Integer.parseInt(markS);
                    String comment = request.getParameter("txtComment");
                    java.util.Date utilDate = new java.util.Date();
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
                    //---------------------------------------------------------------------------
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;

                    boolean test = tsbl.vote(name, idImgContest, mark, comment, sqlDate);
                    if (test) {
                        out.print("Vote OK");
                    } else {
                        out.print("You are not vote or voted");
                    }
                } else if (action.equals("ViewMyVote")) {
                    String name = request.getParameter("txtUsername");
                    String idConS = request.getParameter("idContest");
                    int idContest = Integer.parseInt(idConS);
                    //---------------------------------------------------------------------
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    Collection viewVote = tsbl.viewVote(name, idContest);
                    System.out.println(viewVote);
                    request.setAttribute("ViewVote", viewVote);
                    RequestDispatcher rd = request.getRequestDispatcher("ViewVote.jsp");
                    rd.forward(request, response);
                } else if (action.equals("Report")) {
                    String fromdate = request.getParameter("txtFromDate");
                    String toDate = request.getParameter("txtToDate");
                    String idContest = request.getParameter("txtIdContest");
                    System.out.println(idContest);
                    int idCon = Integer.parseInt(idContest);
                    //------------------------------------------------------------------------------
                    Context ctx = new InitialContext();
                    Object obj = ctx.lookup("ProcessLocalJNDI");
                    ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                    java.util.Date d1 = df.parse(fromdate);
                    java.sql.Date sd1 = new java.sql.Date(d1.getTime());
                    java.util.Date d2 = df.parse(toDate);
                    java.sql.Date sd2 = new java.sql.Date(d2.getTime());
                    List<ReportTopContest> list = tsbl.reportTopContest(sd1, sd2, idCon);
                    CreatesContest contest = null;
                    for (int i = 0; i < list.size(); i++) {
                        System.out.println("ID:" + list.get(i).getIdmgcontest() + "Mark: " + list.get(i).getTotalmark());
                        contest = list.get(0).getContest();
                    }
                    System.out.println(contest);
                    request.setAttribute("Contest", contest);
                    request.setAttribute("Result", list);

                    RequestDispatcher rd = request.getRequestDispatcher("ReportTopContest.jsp");
                    rd.forward(request, response);
                } else if (action.equals("getcontent")) {
                    String id = request.getParameter("id");
                    out.println(id);
                    return;
                }
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
                Iterator iter = items.iterator();
                Hashtable params = new Hashtable();
                String fileName = null;
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        //todo
                        params.put(item.getFieldName(), item.getString());
                    } else {
                        try {
                            String itemName = item.getName();
                            fileName = itemName.substring(
                                    itemName.lastIndexOf("\\") + 1);
                            System.out.println("path " + fileName);
                            String RealPath = getServletContext().getRealPath("/")
                                    + "Images\\" + fileName;
                            System.out.println("Rpath " + RealPath);
                            File savedFile = new File(RealPath);
                            item.write(savedFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }//end while
//------------------------------------------------------------------------------
                String name = (String) params.get("txtUsername");
                String infoImage = (String) params.get("txtInfoImage");
//                    String pathImage = (String) params.get("filebox");
                String idCon = (String) params.get("txtIdContest");
                int idContest = Integer.parseInt(idCon);
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                String today = sdf.format(date.getTime());
//                out.print("txtUsername:" + name + "</br>");
//                out.print("txtUsername:" + infoImage + "</br>");
//                out.print("txtUsername:" + fileName + "</br>");
//                out.print("txtUsername:" + idContest + "</br>");
//                out.print("txtUsername:" + today + "</br>");
//                out.print("<img src='Images/"+fileName+"'/>");
//------------------------------------------------------------------------------
                Context ctx = new InitialContext();
                Object obj = ctx.lookup("ProcessLocalJNDI");
                ProcessBeanLocal tsbl = (ProcessBeanLocal) obj;
                boolean test = tsbl.uploadImage(infoImage, fileName, today, name, idContest);
                if (test) {
                    out.print("Upload OK!");
                } else {
                    out.print("You are upload");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
